package com.summer.safe.controller.system;

import com.summer.safe.base.Page;
import com.summer.safe.config.annotation.ResultWrapper;
import com.summer.safe.config.result.ResultCode;
import com.summer.safe.system.entity.Role;
import com.summer.safe.system.service.RoleService;
import com.summer.safe.system.service.SystemService;
import com.summer.safe.utils.StringUtils;
import com.summer.safe.utils.ToolUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限管理controller
 *
 */
@Controller
@RequestMapping("/sys/role")
public class RoleController {

    private String PREFIX = "/system/role/";
    @Autowired
    public RoleService roleService;
    @Autowired
    private SystemService systemService;


    @ModelAttribute("role")
    public Role get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return roleService.get(id);
        } else {
            return new Role();
        }
    }

    /**
     * 跳转到角色管理主页
     */
    @RequiresPermissions("sys:role:view")
    @GetMapping("")
    public String index(Model model, Role role) {
        model.addAttribute("role", role);
        return PREFIX + "rolelist.html";

    }



    @RequestMapping(value = "dataList")
    @ResultWrapper
    public Page list(Role role, HttpServletRequest request) {
        Page<Role> page = roleService.findPage(new Page(request), role);
        return page;
    }

    @RequiresPermissions("sys:role:edit")
    @GetMapping("/form")
    public String form(Role role, Model model) {
        role=roleService.get(role.getId());
        model.addAttribute("role", role);
        model.addAttribute("menuList", systemService.findAllMenu());
        return  PREFIX + "roleform.html";
    }


    @RequestMapping("/delete")
    @ResultWrapper(ResultCode.SUCCESS_DELETE)
    public void delete(Role role) {
        role=roleService.get(role.getId());
        roleService.delete(role);
    }

    @PostMapping("/save")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void save(Role role) {
        //判断是否为演示模式
        ToolUtil.DemoMode();

        systemService.saveRole(role);
     }

    /**
     * 权限分配
     */

    @GetMapping("/authority")
    public String authority(Role role, Model model) {
        role=roleService.get(role.getId());
        model.addAttribute("role", role);
        model.addAttribute("officeList", systemService.findAllOffice());
        return  PREFIX + "authority.html";
    }


    @PostMapping("/saveRoleOffice")
    @ResultWrapper(ResultCode.SUCCESS_SAVE)
    public void saveRoleOffice(Role role) {
        systemService.saveRoleOffice(role);

    }
}
